<?php if(!defined('SPRITCH')) { exit(); }

// Spritch - An opensource PHP5 web framework

// Author: Luca Degasperi
// Licence: GNU GPL
// Site: http://www.spritch.org/

// Class: Date
// Summary: This class provides date format functions
// Since: 0.9.1

class date_helper extends helper
{
	private $date_format = '';
	private $language;
	private $standards = array
	(
		'ATOM'      => '%Y-%m-%dT%H:%i:%s%Q',
		'COOKIE'    => '%l, %d-%M-%y %H:%i:%s UTC',
		'ISO8601'   => '%Y-%m-%dT%H:%i:%s%O',
		'RFC822'    => '%D, %d %M %y %H:%i:%s %O',
		'RFC850'    => '%l, %d-%M-%y %H:%m:%i UTC',
		'RFC1036'   => '%D, %d %M %y %H:%i:%s %O',
		'RFC1123'   => '%D, %d %M %Y %H:%i:%s %O',
		'RSS'       => '%D, %d %M %Y %H:%i:%s %O',
		'W3C'       => '%Y-%m-%dT%H:%i:%s%Q',
		'CUSTOM'    => '%j %F %Y',
	);

	public function __construct()
	{
		$this->date_format = $this->configuration->get('date_format','CUSTOM');
		date_default_timezone_set($this->configuration->get('time_zone','GMT'));
		$this->language = get('language.helper');
	}

	//standard to unix
	public function to_unix($date)
	{
		return strtotime($date);
	}

	//unix to standard
	public function to_standard($standard = 'RFC822',$unix = null)
	{		
		if(is_null($unix))
			$unix = $this->now();
		if(array_key_exists($standard,$this->standards))
		{
			$datestr = str_replace('%\\','',preg_replace("/([a-z]+?){1}/i", "\\\\\\1",$this->standards[$standard]));
			return $this->to_language($datestr,$unix);
		}
		else
		{
			return false;
		}
	}

	public function from_mysql($mysql,$date_format = null)
	{
		if(is_null($date_format))
			$date_format = $this->date_format;
		return $this->to_standard($date_format,$this->to_unix($mysql));
	}

	//unix timestamp
	public function now()
	{
		return time();
	}

	public function compare($date1,$date2)
	{
		$date1 = $this->to_unix($date1);
		$date2 = $this->to_unix($date2);
		if($date1 > $date2)
			return true;
		else
			return false;
	}

	// converts a date to a specified language
	private function to_language($datestr,$unix)
	{
		$datearr = getdate($unix);
		$datemonth = $datearr['month'];
		$dateday = $datearr['weekday'];
		$datem = substr($datemonth,0,3);
		$dated = substr($dateday,0,3);
		$date = date($datestr,$unix);
		return $date;
	}
}
?>